package com.ygy.yfzx.license;

import com.ygy.yfzx.license.data.CustomKeyStoreParam;
import com.ygy.yfzx.license.data.LicenseVerifyParam;
import de.schlichtherle.license.*;

import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * License校验类
 *
 * @author shengye
 * @date 2024/3/12 9:02
 */
public class LicenseVerify {
    /**
     * 安装License证书,读取证书相关的信息, 在bean加入容器的时候自动调用
     */
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1. 安装证书
        try {
            LicenseManagerHolder.init(initLicenseParam(param));
            LicenseManager licenseManager = LicenseManagerHolder.getInstance();
            licenseManager.uninstall();

            result = licenseManager.install(new File(param.getLicensePath()));
            System.out.println(MessageFormat.format("证书安装成功，证书有效期：{0} - {1}", format.format(result.getNotBefore()), format.format(result.getNotAfter())));
        } catch (Exception e) {
            System.out.println("证书安装失败！" + e);
        }

        return result;
    }

    /**
     * 校验License证书
     */

    public boolean verify() {
        try {
            //2. 校验证书
            LicenseManager licenseManager = LicenseManagerHolder.getInstance();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            LicenseContent licenseContent = licenseManager.verify();
            String msg = MessageFormat.format("证书校验通过，证书有效期：{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter()));
            System.out.println(msg);
            return true;
        } catch (Exception e) {
            System.out.println("证书校验失败！" + e);
            return false;
        }
    }

    /**
     * 初始化证书生成参数
     *
     * @param param License校验类需要的参数
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());

        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , param.getPublicKeysStorePath()
                , param.getPublicAlias()
                , param.getStorePass()
                , null);

        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }

}
